import { useAtomValue } from 'jotai'
import React, { useState } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from 'v1-components'
import { Check, Copy } from 'lucide-react'
import { answerAtom, selectedVersionAtom } from '@/store/question'

export function DownloadDialog({ children }) {
  const selectedVersion = useAtomValue(selectedVersionAtom)
  const answers = useAtomValue(answerAtom)
  const [copied, setCopied] = useState(false)

  function onCopy() {
    setCopied(true)
    copyToClipBoard(`npx inula-codegen ${answers[selectedVersion]}`)
    setTimeout(() => {
      setCopied(false)
    }, 2000)
  }
  function copyToClipBoard(command: string): void {
    navigator.clipboard.writeText(command)
  }
  return (
    <Dialog>
      <DialogTrigger asChild>
        {children}
      </DialogTrigger>
      <DialogContent className="sm:max-w-[640px]">
        <DialogHeader>
          <DialogTitle>下载AI代码</DialogTitle>
        </DialogHeader>
        <section>
          <h1>
            步骤1： 拷贝下载命令
          </h1>
          <div className="relative my-4">
            <div className="bg-gray-900 text-white p-4 rounded-md">
              <div className="flex justify-between items-center mb-2">
                <span className="text-gray-400">下载命令:</span>
                <button onClick={() => { onCopy() }} className="code bg-gray-800 hover:bg-gray-700 text-gray-300 px-3 py-1 rounded-md" data-clipboard-target="#code">
                  {copied ? <Check /> : <Copy /> }
                </button>
              </div>
              <div className="overflow-x-auto">
                <pre id="code" className="text-gray-300">
                  <code className="text-yellow-200">
                    npx inula-codegen
                    {' '}
                    {answers[selectedVersion]}
                  </code>
                </pre>
              </div>
            </div>
          </div>
        </section>
        <section>
          步骤2：
          前往你的项目根目录，粘贴并执行命令。
        </section>
        <section>
          步骤3：代码会自动下载到你的项目中， 从`lib/components`导入组件即可使用
        </section>
      </DialogContent>
    </Dialog>
  )
}
